import { editProfile,logout,setupUserProfile} from "./auth.js";
window.editProfile = editProfile;
window.logout = logout;
window.setupUserProfile = setupUserProfile;
// 防抖函数
export function debounce(func, delay) {
    let timer;
    return function() {
        const context = this;
        const args = arguments;
        clearTimeout(timer);
        timer = setTimeout(() => {
            func.apply(context, args);
        }, delay);
    };
}

export async function displayCollectedQuestions(scrollPosition = null) {
    try {
        // 获取用户信息
        const urlParams = new URLSearchParams(window.location.search);
        const username = urlParams.get('username');
        const userResponse = await fetch(`/user-info?username=${escapeHTML(username)}`);
        const data = await userResponse.json();
        const userId = data.user_id;

        if (!username) {
            showError('用户名不能为空');
            return;
        }
        await setupUserProfile(username);
        // 获取用户待提交练习
        /*const todoPracticesResponse = await fetch(`/api/user-todo-practices/${escapeHTML(userId}`);
        const todoPractices = await todoPracticesResponse.json();*/
        const response = await fetch(`/get-selected-courses?username=${escapeHTML(username)}`);
        const courses = await response.json();
        let practiceIds = [];
        for (const course of courses) {
            const response = await fetch(`/practice/course/${escapeHTML(course.course_code)}`);
            const practices = await response.json();
            practiceIds = practiceIds.concat(practices.map(p => p.practice_id));
        }
        const todoPractices = await Promise.all(
            practiceIds.map(async practiceId => {
                const response = await fetch(`/practice/detail/${escapeHTML(practiceId)}?userId=${escapeHTML(userId)}`);
                return await response.json();
            })
        );
        // 获取已提交练习
        const submittedPractices = [];
        for (const practice of todoPractices) {
            const checkResponse = await fetch(`/check-submission?userId=${escapeHTML(userId)}&practiceId=${escapeHTML(practice.practice_id)}`);
            const checkData = await checkResponse.json();
            if (checkData.hasSubmission) {
                submittedPractices.push(practice);
            }
        }

        // 填充选择框选项
        const practiceFilter = document.getElementById('practiceFilter');
        submittedPractices.forEach(practice => {
            const option = document.createElement('option');
            option.value = practice.practice_id;
            option.textContent = practice.practice_name;
            practiceFilter.appendChild(option);
        });

        // 添加选择框事件监听器，使用防抖机制
        practiceFilter.addEventListener('change', debounce(async () => {
            const selectedPracticeId = practiceFilter.value;
            await filterCollectedQuestions(selectedPracticeId, userId);
        }, 150));

        // 初始显示所有已收藏题目
        await filterCollectedQuestions('all', userId);
        if (scrollPosition !== null) {
            setTimeout(() =>{
                window.scrollTo(0, scrollPosition);
            }, 50);
        }
    } catch (error) {
        console.error('加载题目失败:', error);
        document.getElementById('questionList').innerHTML = `
            <div class="bg-white p-4 rounded-lg text-center text-red-500">
                加载题目失败: ${escapeHTML(error.message)}
            </div>
        `;
    }
}

export async function filterCollectedQuestions(selectedPracticeId, userId) {
    // 获取用户收藏的题目信息
    const response = await fetch(`/api/user-collected-questions/${escapeHTML(userId)}`);
    const collectedQuestions = await response.json();

    const questionList = document.getElementById('questionList');
    questionList.innerHTML = '';

    let questionNumber = 1;
    for (const question of collectedQuestions) {
        if (selectedPracticeId !== 'all' && question.practice_id !== selectedPracticeId) {
            continue;
        }

        const { question_type, practice_id, question_order } = question;
        let questionData;

        try {
            // 根据题目类型调用对应的API获取详细信息
            if (question_type === 'choice') {
                const choiceResponse = await fetch(`/api/practice/${practice_id}/choice-question/${question_order}`);
                const { success, data } = await choiceResponse.json();
                if (!success || !data) continue;
                questionData = data;

                // 获取练习名称
                const practiceResponse = await fetch(`/practice/detail/${escapeHTML(practice_id)}`);
                const practiceData = await practiceResponse.json();
                const practiceName = practiceData.practice_name;

                const questionCard = document.createElement('div');
                questionCard.className = 'bg-white p-4 rounded-lg shadow-sm mb-4';
                // 修改后的选择题卡片
                questionCard.innerHTML = `
                <div class="bg-gradient-to-br from-white to-blue-50 rounded-xl border border-blue-100 shadow-md overflow-hidden">
                    <!-- 标题栏 -->
                    <div class="bg-gradient-to-r from-blue-500 to-blue-600 px-6 py-3">
                        <div class="flex justify-between items-center">
                            <h3 class="text-lg font-bold text-white">选择题</h3>
                            <span class="bg-white text-blue-600 rounded-full px-3 py-1 text-sm font-medium">${escapeHTML(questionNumber)}</span>
                        </div>
                    </div>
                    
                    <!-- 内容区 -->
                    <div class="p-6">
                        <div class="text-gray-700 text-lg mb-4 leading-relaxed">
                            ${escapeHTML(questionData.question)}
                        </div>
                        
                        <ul class="space-y-3">
                            <li class="flex items-start bg-white/80 p-3 rounded-lg border border-blue-100">
                                <span class="bg-blue-100 text-blue-700 font-bold px-3 py-1 rounded mr-3">A</span>
                                <span>${escapeHTML(questionData.option_a)}</span>
                            </li>
                            <li class="flex items-start bg-white/80 p-3 rounded-lg border border-blue-100">
                                <span class="bg-blue-100 text-blue-700 font-bold px-3 py-1 rounded mr-3">B</span>
                                <span>${escapeHTML(questionData.option_b)}</span>
                            </li>
                            ${escapeHTML(questionData.option_c) ? `
                            <li class="flex items-start bg-white/80 p-3 rounded-lg border border-blue-100">
                                <span class="bg-blue-100 text-blue-700 font-bold px-3 py-1 rounded mr-3">C</span>
                                <span>${escapeHTML(questionData.option_c)}</span>
                            </li>` : ''}
                            ${escapeHTML(questionData.option_d) ? `
                            <li class="flex items-start bg-white/80 p-3 rounded-lg border border-blue-100">
                                <span class="bg-blue-100 text-blue-700 font-bold px-3 py-1 rounded mr-3">D</span>
                                <span>${escapeHTML(questionData.option_d)}</span>
                            </li>` : ''}
                        </ul>
                    </div>
                    
                    <!-- 底部信息栏 -->
                    <div class="bg-blue-50/70 px-6 py-4 border-t border-blue-100 flex justify-between items-center">
                        <div class="flex items-center">
                            <i class="fa-solid fa-book text-blue-500 mr-2"></i>
                            <span class="text-gray-600">所属练习：</span>
                            <span class="ml-1 font-medium text-blue-700">${escapeHTML(practiceName)}</span>
                        </div>
                        <div class="collect-section"></div>
                    </div>
                </div>
                `;

                // 创建收藏按钮容器
                const collectSection = document.createElement('div');
                collectSection.className = 'collect-section';

                // 创建并添加收藏按钮
                const isCollected = true; // 已收藏
                const collectButton = await createCollectButton(questionData, practice_id, userId, isCollected);
                collectSection.appendChild(collectButton);

                // 将收藏按钮容器添加到问题卡片
                questionCard.appendChild(collectSection);

                questionList.appendChild(questionCard);
                questionNumber++;
            } else if (question_type === 'fill') {
                const fillResponse = await fetch(`/api/practice/${escapeHTML(practice_id)}/fill-question/${escapeHTML(question_order)}`);
                const { success, data } = await fillResponse.json();
                if (!success || !data) continue;
                questionData = data;

                // 获取练习名称
                const practiceResponse = await fetch(`/practice/detail/${escapeHTML(practice_id)}`);
                const practiceData = await practiceResponse.json();
                const practiceName = practiceData.practice_name;

                const questionCard = document.createElement('div');
                questionCard.className = 'bg-white p-4 rounded-lg shadow-sm mb-4';
                // 修改后的填空题卡片
                questionCard.innerHTML = `
<div class="bg-gradient-to-br from-white to-green-50 rounded-xl border border-green-100 shadow-md overflow-hidden mb-6">
    <!-- 标题栏 - 保持与其他题型一致的样式 -->
    <div class="bg-gradient-to-r from-green-500 to-green-600 px-6 py-3">
        <div class="flex justify-between items-center">
            <h3 class="text-lg font-bold text-white">填空题</h3>
            <span class="bg-white text-green-600 rounded-full px-3 py-1 text-sm font-medium">${escapeHTML(questionNumber)}</span>
        </div>
    </div>
    
    <!-- 内容区 - 保持您原有的结构 -->
    <div class="p-6">
        <div class="text-gray-700 text-lg leading-relaxed">
            ${escapeHTML(questionData.question).replace(/__/g, '<span class="inline-block mx-1 px-3 py-1 bg-green-50 border border-green-200 rounded text-sm">填空</span>')}
        </div>
    </div>
    
    <!-- 底部信息栏 -->
    <div class="bg-green-50/70 px-6 py-4 border-t border-green-100 flex justify-between items-center">
        <div class="flex items-center">
            <i class="fa-solid fa-book text-green-500 mr-2"></i>
            <span class="text-gray-600">所属练习：</span>
            <span class="ml-1 font-medium text-green-700">${escapeHTML(practiceName)}</span>
        </div>
        <div class="collect-section"></div>
    </div>
</div>
`;

                // 创建收藏按钮容器
                const collectSection = document.createElement('div');
                collectSection.className = 'collect-section';

                // 创建并添加收藏按钮
                const isCollected = true; // 已收藏
                const collectButton = await createCollectButton(questionData, practice_id, userId, isCollected);
                collectSection.appendChild(collectButton);

                // 将收藏按钮容器添加到问题卡片
                questionCard.appendChild(collectSection);

                questionList.appendChild(questionCard);
                questionNumber++;
            } else if (question_type === 'essay') {
                const essayResponse = await fetch(`/api/practice/${escapeHTML(practice_id)}/essay-question/${escapeHTML(question_order)}`);
                const { success, data } = await essayResponse.json();
                if (!success || !data) continue;
                questionData = data;

                // 获取练习名称
                const practiceResponse = await fetch(`/practice/detail/${escapeHTML(practice_id)}`);
                const practiceData = await practiceResponse.json();
                const practiceName = practiceData.practice_name;

                const questionCard = document.createElement('div');
                questionCard.className = 'bg-white p-4 rounded-lg shadow-sm mb-4';
                questionCard.innerHTML = `
<div class="bg-gradient-to-br from-white to-purple-50 rounded-xl border border-purple-100 shadow-md overflow-hidden">
    <!-- 标题栏 -->
    <div class="bg-gradient-to-r from-purple-500 to-purple-600 px-6 py-3">
        <div class="flex justify-between items-center">
            <h3 class="text-lg font-bold text-white">解答题</h3>
            <span class="bg-white text-purple-600 rounded-full px-3 py-1 text-sm font-medium">${escapeHTML(questionNumber)}</span>
        </div>
    </div>
    
    <!-- 内容区 -->
    <div class="p-6">
        <div class="text-gray-700 text-lg mb-4 leading-relaxed">
            ${escapeHTML(questionData.question)}
        </div>
        
        <div class="bg-white/80 p-5 rounded-lg border border-purple-100">
            <div class="text-gray-600 italic">
                <i class="fa-solid fa-pen-nib text-purple-500 mr-2"></i>
                请在此处书写完整解答过程...
            </div>
        </div>
    </div>
    
    <!-- 底部信息栏 -->
    <div class="bg-purple-50/70 px-6 py-4 border-t border-purple-100 flex justify-between items-center">
        <div class="flex items-center">
            <i class="fa-solid fa-book text-purple-500 mr-2"></i>
            <span class="text-gray-600">所属练习：</span>
            <span class="ml-1 font-medium text-purple-700">${escapeHTML(practiceName)}</span>
        </div>
        <div class="collect-section"></div>
    </div>
</div>
`;

                // 创建收藏按钮容器
                const collectSection = document.createElement('div');
                collectSection.className = 'collect-section';

                // 创建并添加收藏按钮
                const isCollected = true; // 已收藏
                const collectButton = await createCollectButton(questionData, practice_id, userId, isCollected);
                collectSection.appendChild(collectButton);

                // 将收藏按钮容器添加到问题卡片
                questionCard.appendChild(collectSection);

                questionList.appendChild(questionCard);
                questionNumber++;
            }
        } catch (error) {
            console.error(`获取${escapeHTML(question_type)}题目失败:`, error);
            continue; // 跳过当前题目，继续处理下一个
        }
    }

    // 如果没有收藏的题目
    if (questionNumber === 1) {
        questionList.innerHTML = `
    <div class="bg-transparent p-8 rounded-lg text-center">
        <div class="flex flex-col items-center justify-center">
            <!-- 图标 -->
            <div class="w-20 h-20 rounded-full bg-white/10 flex items-center justify-center mb-4">
                <i class="fa-solid fa-bookmark text-3xl text-blue-300"></i>
            </div>
            
            <!-- 提示文字 -->
            <h3 class="text-xl font-medium text-white mb-2">收藏夹空空如也</h3>
            <p class="text-blue-100 mb-6 max-w-md">您还没有收藏任何题目，快去练习中发现值得收藏的题目吧！</p>
            
            <!-- 返回按钮 -->
            <button id="goToPracticeBtn" class="bg-gradient-to-r from-blue-500 to-indigo-600 text-white px-6 py-3 rounded-full flex items-center justify-center shadow-lg hover:shadow-xl transition-all duration-300">
                <i class="fa-solid fa-arrow-left mr-2"></i> 返回练习列表
            </button>
        </div>
    </div>
`;
document.getElementById('goToPracticeBtn').addEventListener('click', () => {
    // 这里添加跳转到练习页面的逻辑
    window.location.href = 'todo-practice.html'+window.location.search; // 示例跳转
});
    }
}

// 显示错误信息
function showError(message) {
    const errorElement = document.createElement('div');
    errorElement.className = 'bg-red-50 border border-red-200 text-red-700 p-4 rounded-lg mb-4';
    errorElement.innerHTML = `
        <div class="flex items-start">
            <div class="flex-shrink-0 pt-0.5">
                <i class="fa-solid fa-exclamation-circle text-red-500"></i>
            </div>
            <div class="ml-3">
                <h3 class="text-sm font-medium">加载失败</h3>
                <div class="mt-1 text-sm">
                    ${escapeHTML(message)}
                </div>
            </div>
        </div>
    `;
    document.getElementById('questionList').appendChild(errorElement);
}

// 创建收藏按钮
export async function createCollectButton(question, practiceId, userId, isCollected) {
    const button = document.createElement('button');
    button.className = 'collect-btn';

    // 更新按钮外观的函数
// 修改后的收藏按钮（在createCollectButton函数中）
 function updateButtonUI() {
    const starIcon = isCollected 
        ? '<i class="fa-solid fa-star text-red-400 mr-2"></i>' 
        : '<i class="fa-regular fa-star text-gray-400 mr-2"></i>';

    const buttonText = isCollected ? '取消收藏' : '收藏题目';
    button.innerHTML = `
        ${starIcon}
        <span class="font-medium">${buttonText}</span>
    `;
}

    // 初始化按钮外观
    updateButtonUI();
    button.style.color = 'gray';

    button.addEventListener('click', async () => {
        try {
            let response, data;

            if (isCollected) {
                // 取消收藏
                response = await fetch('/uncollect-question', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ practiceId, userId, questionOrder: question.question_order })
                });
                data = await response.json();
                if (data.message === '题目已取消收藏') {
                    isCollected = false;
                    updateButtonUI();
                    await displayCollectedQuestions(window.scrollY);
                }
            } else {
                // 收藏题目
                response = await fetch('/collect-question', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ practiceId, userId, questionOrder: question.question_order })
                });
                data = await response.json();
                if (data.message === '题目已收藏') {
                    isCollected = true;
                    updateButtonUI();
                }
            }
        } catch (error) {
            console.error('收藏/取消收藏题目失败:', error);
        }
    });

    return button;
}

// 页面加载完成后显示已收藏题目
window.addEventListener('load', displayCollectedQuestions(null));

document.addEventListener('DOMContentLoaded', function() {
    // 获取"返回"链接元素
    const backLink = document.querySelector('ul.flex li:first-child a');
    if (backLink) {
        // 添加点击事件监听器
        backLink.addEventListener('click', function(event) {
            event.preventDefault(); 
            window.location.href ='todo-practice.html'+window.location.search;
        });
    }
});

function escapeHTML(str) {
    if (typeof str !== 'string') return str;
    return str.replace(/[&<>"']/g, function (match) {
    switch (match) {
    case '&':
    return '&amp;';
    case '<':
    return '&lt;';
    case '>':
    return '&gt;';
    case '"':
    return '&quot;';
    case "'":
    return '&#039;';
}
 });
}
